package com.gjxjl.jdbc.gateway.handler;

import io.netty.buffer.ByteBuf;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

public class BackendHandler extends ChannelInboundHandlerAdapter {
    private static final Logger logger = LogManager.getLogger(BackendHandler.class);

    private final Channel clientChannel;

    public BackendHandler(Channel clientChannel) {
        this.clientChannel = clientChannel;
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        if (msg instanceof ByteBuf) {
            ByteBuf packet = (ByteBuf) msg;

            // 记录后端响应
            logPacket("PROXY <- BACKEND", packet);

            // 转发到客户端
            if (clientChannel != null && clientChannel.isActive()) {
                clientChannel.writeAndFlush(packet.retain());
            }
        }
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        logger.info("Backend connection closed");
        if (clientChannel != null && clientChannel.isActive()) {
            clientChannel.close();
        }
        super.channelInactive(ctx);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        logger.error("Backend channel exception", cause);
        ctx.close();
    }

    private void logPacket(String direction, ByteBuf packet) {
        try {
            byte[] data = new byte[packet.readableBytes()];
            packet.getBytes(packet.readerIndex(), data);
            logger.debug("{} Packet: {} bytes", direction, data.length);

            if (data.length < 100) {
                logger.trace("{} Data: {}", direction, bytesToHex(data));
            }
        } catch (Exception e) {
            logger.warn("Error logging backend packet", e);
        }
    }

    private String bytesToHex(byte[] bytes) {
        StringBuilder sb = new StringBuilder();
        for (byte b : bytes) {
            sb.append(String.format("%02x ", b));
        }
        return sb.toString();
    }
}
